package com.guys8.cemsbackend.utils;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CrosConfig {
    @Bean
    public CorsFilter corsFilter(){
        CorsConfiguration configuration = new CorsConfiguration();
        //设置放行的原始域
        configuration.addAllowedOriginPattern("*");//放行所有
        //是否允许携带cookie 如果设置位true 则上面的   addAllowedOrigin("*") *不会有效果
        configuration.setAllowCredentials(true);
        //如果setAllowCredentials 设置为true 又想放行所有则需要添加下面这个方法
//        configuration.addAllowedOriginPattern("*");
        //设置客户端可以访问的头  可以设置多个  也可以写*
//        configuration.addExposedHeader("Token");
//        configuration.addExposedHeader("ValidateKey");
        configuration.addExposedHeader("*");
        //设置可以放行的请求方式  可以写具体的请求方式
        configuration.addAllowedMethod("GET");
        configuration.addAllowedMethod("POST");
        configuration.addAllowedMethod("OPTIONS");
        //设置可以允许的请求头
        configuration.addAllowedHeader("*");
        //添加映射路径
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",configuration);
        return new CorsFilter(urlBasedCorsConfigurationSource);

    }
}
